package com.trainingcloud.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport
{
	private static final int FILE_SIZE=16*1024;
	private File upFile;
	private String upFileContentType;
	private String upFileFileName;
	
	public void uploadFile(File source,File target)
	{
		InputStream in = null;
		OutputStream out = null;
		try 
		{
			in = new BufferedInputStream(new FileInputStream(source), FILE_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(target), FILE_SIZE);
			byte[] image = new byte[FILE_SIZE];
			while (in.read(image) > 0) 
			{
				out.write(image);
			}
		}
		catch (IOException ex) 
		{
			ex.printStackTrace();
		}
		finally
		{
			try
			{
				in.close();
				out.close();
			}
			catch (IOException ex)
			{

			}
		}
	}

	
	public String execute() throws Exception
	{
		if(this.upFileFileName==null)
			return "input";
		String filePath = ServletActionContext.getServletContext().getRealPath("images")+"/"+this.upFileFileName;
		File targetFile = new File(filePath);
		uploadFile(upFile, targetFile);
		return "success";
	}
	
	
	public File getUpFile() {
		return upFile;
	}
	public void setUpFile(File upFile) {
		this.upFile = upFile;
	}
	public String getUpFileContentType() {
		return upFileContentType;
	}
	public void setUpFileContentType(String upFileContentType) {
		this.upFileContentType = upFileContentType;
	}
	public String getUpFileFileName() {
		return upFileFileName;
	}
	public void setUpFileFileName(String upFileFileName) {
		this.upFileFileName = upFileFileName;
	}
	
}
